// ThreadTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ThreadTest.h"
#include <process.h>
#include <afxmt.h>

using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

UINT WINAPI ThreadProc(LPVOID lpParam);
static int g_nValue = 0;
CEvent g_Event;

// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		// TODO: code your application's behavior here.
		HANDLE hHandle[4] = {0};
		const int nCount = 4;
		DWORD dwThreadID = 0;

		clock_t start = clock();
		for (int i = 0; i < nCount; i++)
		{
			hHandle[i] = (HANDLE)::_beginthreadex(
				NULL,
				0,
				ThreadProc,
				0,
				0,
				0
				);
		}

		g_Event.SetEvent();
		::WaitForMultipleObjects(nCount, hHandle, TRUE, INFINITE);

		for (int i = 0; i < nCount; i++)
		{
			::CloseHandle(hHandle[i]);
		}

		_tprintf(_T("Value: %d\n"), g_nValue);

		clock_t end = clock();

		double difftime = (end - start) / 1000.0;
		CString strDifftime;
		strDifftime.Format(_T("difftime: %f\n"), difftime);
		_tprintf(strDifftime);
	}

	return nRetCode;
}

UINT WINAPI ThreadProc( LPVOID lpParam )
{
	//::WaitForSingleObject(g_Event.m_hObject, INFINITE);
	for (int i = 0; i < 1000000; i++)
	{
		::WaitForSingleObject(g_Event.m_hObject, INFINITE);
		g_nValue++;
		g_Event.SetEvent();
	}
	//g_Event.SetEvent();

	return EXIT_SUCCESS;
}